import OrderTable from '@/pages/Order/components/OrderTable'
import OrderUpdateModal from '@/pages/Order/components/OrderUpdateModal'
import { OrderUpdateDTO, OrderVO, saveOrder, updateOrder } from '@/services/OrderService'
import { PageContainer } from '@ant-design/pro-components'
import { ActionType } from '@ant-design/pro-table'
import { useRef, useState } from 'react'

const Order = () => {
  // 编辑操作
  const [updateModalState, setUpdateModalState] = useState(false)
  const [currentOrder, setCurrentOrder] = useState<OrderVO | undefined>()
  // 表格引用
  const tableRef = useRef<ActionType>()
  const updateEvent = async (record: OrderVO) => {
    // 打开模态框
    let _record: OrderVO = JSON.parse(JSON.stringify(record))
    _record.goodsPrice = _record.goodsPrice / 100
    _record.alreadyPay = _record.alreadyPay / 100
    _record.realPrice = _record.realPrice / 100
    _record.arrears = _record.arrears / 100
    setCurrentOrder(_record)
    setUpdateModalState(true)
  }

  const saveEvent = async () => {
    // 打开模态框
    setCurrentOrder(undefined)
    setUpdateModalState(true)
  }

  // 提交修改
  const onUpdateFinish = async (formData: any) => {
    let dto: OrderUpdateDTO = JSON.parse(JSON.stringify(formData))
    dto.arrears = dto.realPrice - dto.alreadyPay
    const fun = currentOrder ? updateOrder : saveOrder
    let response = await fun(dto)
    if (response) {
      tableRef.current?.reload()
      return true
    }
    return false
  }

  return (
    <PageContainer title="订单">
      {/*订单表格 开始*/}
      <OrderTable tableRef={tableRef} onSave={saveEvent} onUpdate={updateEvent} />
      {/*订单表格 结束*/}

      {/*修改模态框 开始*/}
      <OrderUpdateModal
        scene="order"
        order={currentOrder}
        open={updateModalState}
        onOpenChange={setUpdateModalState}
        onFinish={onUpdateFinish}
      />
      {/*修改模态框 结束*/}
    </PageContainer>
  )
}

export default Order
